#!/bin/bash

# ----------------------------------------------------------------------
# Filename:   addrules.sh
# Version:    1.0
# Date:       2013/12/05
# Author:     huijing.hei
# Email:      huijing.hei@cs2c.com.cn
# Summary:    03系统安全功能-03IPTables-02IPTables基本策略和简单规则配置-03规则添加
# Notes:       ***
# Copyright:    China Standard Software Co., Ltd.
# History：     
#             Version 1.0, 2013/12/05
#             - iptables add rules.
# ----------------------------------------------------------------------

##! @TODO:  iptables start
##! @AUTHOR: huijing.hei
##! @VERSION: 1.0 
##! @OUT: 0 => success; 1 => failure

function DoSetup()
{
    trap DoCleanup INT EXIT
    serv=iptables
    CheckServiceExists  ${serv}
    EchoResult "check service"

#    StatusDaemon ${serv}
#
#    # start
#    if [ $? -ne 0 ]
#    then
#        echo "${serv} is stopped"
#        StartDaemon ${serv}
#        EchoResult "service ${serv} start"
#    else
#        echo "${serv} is running..."
#    fi
#
#    # check iptablesd start
#    StatusDaemon ${serv} && lsmod | grep ip_tables
#    EchoResult "${serv} : start"

    # tmpdir
    TMPDIR=/tmp/iptables$$
    mkdir ${TMPDIR}
    EchoResult "mkdir ${TMPDIR}"

    # clear iptables rules
    iptables -F
    EchoResult "iptables -F"

    iptables -P INPUT ACCEPT
    iptables -P OUTPUT ACCEPT

}

##! @TODO:  iptables add rules
##! @AUTHOR: huijing.hei
##! @VERSION: 1.0 
##! @OUT: 0 => success; 1 => failure

function DoTest()
{
    local TMPOUT=${TMPDIR}/tmpout
    # iptables add rules
    iptables -t filter -A INPUT -s 127.0.0.1 -p icmp -j DROP
    EchoResult "iptables -t filter"

    # check
    iptables -vL INPUT > ${TMPOUT} 2>&1
    grep -c "DROP *icmp" ${TMPOUT} 
    EchoResult "check added rules: iptables -t filter -A INPUT -s 127.0.0.1 -p icmp -j DROP"

    # ping, should fail
    ! ping -c 2 127.0.0.1
    EchoResult "add iptables rules, ping 127.0.0.1, should fail"

    # insert rules
    iptables -I INPUT -s 127.0.0.1 -p icmp -j ACCEPT
    EchoResult "iptables -I INPUT -s 127.0.0.1 -p icmp -j ACCEPT"

    # ping, should success
    ping -c 2 127.0.0.1
    EchoResult "add iptables rules, ping 127.0.0.1, should success"

}

##! @TODO: cleanup
##! @AUTHOR: huijing.hei
##! @VERSION: 1.0 
##! @OUT: 0 => success; 1 => failure

function DoCleanup()
{
    iptables -F
    EchoResult  "iptables -F"

    [ -e ${TMPDIR} ] && rm -rf ${TMPDIR}
}

# include lib files
if [ -z "$SFROOT" ]
then
    echo "SFROOT is null"
    exit 1
fi

. ${SFROOT}/lib/Echo.sh
. ${SFROOT}/lib/NetOps.sh

DoSetup
DoTest
